import axios from 'axios'

// 配置基础URL
const API_BASE_URL = 'http://localhost:8081'

// 创建axios实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 班级管理API
export const classAPI = {
  // 创建班级
  createClass: (classData) => api.post('/api/classes', classData),
  
  // 获取班级信息
  getClass: (classId) => api.get(`/api/classes/${classId}`),
  
  // 获取课程班级
  getClassesByCourse: (courseId) => api.get(`/api/classes/course/${courseId}`),
  
  // 获取教师班级
  getTeacherClasses: (courseId, teacherId) => api.get(`/api/classes/course/${courseId}/teacher/${teacherId}`),
  
  // 获取班级学生
  getClassStudents: (classId) => api.get(`/api/classes/${classId}/students`),
  
  // 获取班级学生ID
  getClassStudentIds: (classId) => api.get(`/api/classes/${classId}/students/ids`),
  
  // 获取班级教师ID
  getClassTeacherIds: (classId) => api.get(`/api/classes/${classId}/teachers/ids`),
  
  // 添加学生到班级
  addStudentToClass: (classId, studentId) => api.post(`/api/classes/${classId}/students/${studentId}`),
  
  // 从班级移除学生
  removeStudentFromClass: (classId, studentId) => api.delete(`/api/classes/${classId}/students/${studentId}`),
  
  // 获取用户在课程中的班级ID
  getUserClassId: (courseId, userId) => api.get(`/api/classes/course/${courseId}/user/${userId}/id`),
  
  // 检查学生是否已加入班级
  checkStudentJoined: (courseId, studentId) => api.get(`/api/classes/course/${courseId}/students/${studentId}/joined`),
  
  // 删除班级
  deleteClass: (classId) => api.delete(`/api/classes/${classId}`),
  
  // 检查班级是否存在
  classExists: (classId) => api.get(`/api/classes/${classId}/exists`)
}

export default api